<template>
  <el-button text :bg="isShow" :type="isShow ? 'primary' : ''" @click="handleShow">
    路况信息
  </el-button>
  <article class="announcement-box">
    <el-dialog
      v-model="isShow"
      title="公告信息"
      width="1100"
      draggable
      @close="announcement = ''"
      :modal="false"
    >
      <template #header>
        <div class="my-header">
          <h2>路况信息</h2>
        </div>
      </template>
      <section class="announcement-content">
        <nav class="operation-bar">
          <el-input v-model.trim="keywords" placeholder="请输入关键词" />
          <el-button :icon="Refresh" @click="keywords = ''"></el-button>
          <el-button @click="handleExport(PageTableData, '路况信息')">
            <i class="iconfont icon-export"></i>
          </el-button>
        </nav>
        <el-table :data="PageTableData" height="240" empty-text="暂无数据" border>
          <el-table-column property="userName" label="用户名" align="center" />
          <el-table-column property="type" label="事件类型" align="center" />
          <el-table-column property="position" label="事件地址" align="center" />
          <el-table-column property="sign" label="附近建筑" align="center" />
          <el-table-column property="date" label="发生时间" align="center" show-overflow-tooltip />
          <el-table-column property="describe" label="事件描述" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <div class="button-box" v-if="row.pass == 0">
                <el-button @click="handleUpdate(row)" color="#468f22">通过</el-button>
                <el-button @click="handleDelete(row)" color="#ee9f3e">忽略</el-button>
              </div>
              <div v-else>已审核</div>
            </template>
          </el-table-column>
        </el-table>
      </section>
      <template #footer>
        <!-- total设置成关键词过滤后的数据长度 -->
        <el-pagination
          layout="prev, pager, next"
          :total="filterData.length"
          v-model:current-page="tablePage"
          v-model:page-size="pageSize"
          size="large"
        />
      </template>
    </el-dialog>
  </article>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getCondition, deleteCondition, updateCondition } from '@/api/condition'
import { Refresh } from '@element-plus/icons-vue'
const { map } = defineProps({
  map: {
    type: Object,
    required: true,
  },
})

const wsmLayer = map.getLayers().item(2) //获取瓦片图层
const wsmSource = wsmLayer.getSource() //获取瓦片图层数据源

const isShow = ref(false)

const tableData = ref([])
const tablePage = ref(1)
const pageSize = ref(5)

const keywords = ref('')
const announcement = ref('')

// 关键词过滤
const filterData = computed(() => {
  return tableData.value.filter((item) => {
    if (keywords.value == '') {
      return item
    }
    if (Object.values(item).includes(keywords.value)) {
      return item
    }
  })
})
// 分页数据
const PageTableData = computed(() => {
  const start = (tablePage.value - 1) * pageSize.value
  const end = start + pageSize.value
  const filteredData = filterData.value.slice(start, end) //适用关键词过滤后的数据切片
  return filteredData
})
const handleShow = () => {
  isShow.value = !isShow.value
  if (isShow.value) {
    getData()
  }
}
// 自定义格式化函数（简单示例）
function formatDate(date) {
  return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
}

const getData = async () => {
  const res = await getCondition()
  res.data.forEach((item) => {
    const date = new Date(item.date)
    item.date = formatDate(date)
  })
  tableData.value = res.data
}
const handleDelete = async (row) => {
  try {
    const id = row.id
    await deleteCondition(id)
    getData()
    // 处理响应
  } catch (error) {
    console.error('异步操作失败:', error)
    // 处理错误，例如显示错误消息
  }
}
const handleUpdate = async (row) => {
  try {
    const id = row.id
    const res = await updateCondition(id)
    if (res.code == 1) {
      console.log(res.code)
      addEventTraffic(row)
    }
    getData()
    // 处理响应
  } catch (error) {
    console.error('异步操作失败:', error)
    // 处理错误，例如显示错误消息
  }
}
const addEventTraffic = (row) => {
  //设置当前点要素的几何信息
  const pntObj = new Zondy.Object.GPoint(row.coordinateX, row.coordinateY)
  const featureGeom = new Zondy.Object.FeatureGeometry({
    PntGeom: [pntObj],
  })

  const attValue = ['无编号', row.type, 0, row.date, row.position, '', '', 0]

  //描述点要素的符号参数信息
  const cPntInfo = new Zondy.Object.CPointInfo({
    Angle: 0,
    Color: 6,
    SymHeight: 5,
    SymID: 21,
    SymWidth: 5,
  })
  //设置当前点要素的图形参数信息
  const graphic = new Zondy.Object.WebGraphicsInfo({
    InfoType: 1,
    PntInfo: cPntInfo,
  })
  const feature1 = new Zondy.Object.Feature({
    fGeom: featureGeom,
    GraphicInfo: graphic,
    AttValue: attValue,
    feature: 1,
  })
  feature1.setFType(1)
  const cAttStruct = new Zondy.Object.CAttStruct({
    FldName: [
      '事件编号',
      '事件类型',
      '事件等级',
      '发生时间',
      '发生地点',
      '车牌号',
      '驾驶员',
      '处理状态',
    ],
    FldNumber: 8,
    FldType: ['string', 'string', 'short', 'string', 'string', 'string', 'string', 'short'],
  })
  //创建一个要素数据集
  const featureSet = new Zondy.Object.FeatureSet({
    AttStruct: cAttStruct,
    SFEleArray: [feature1],
  })
  var editService = new Zondy.Service.EditLayerFeature('gdbp://MapGisLocal/wuhan/sfcls/事件', {
    ip: '127.0.0.1',
    port: '8089',
  })
  editService.add(featureSet, onPntSuccess)
}

function onPntSuccess(data) {
  console.log(data)
  // 尝试刷新地图
  wsmSource.updateParams({
    // A: Math.random(),
    TIME: new Date().getTime(), //唯一性标识, 用于map区分, 强制刷新缓存, 可以是任意无关属性名和值
  })
}
</script>

<style lang="scss" scoped>
.announcement-box {
  :deep(.el-dialog) {
    .my-header {
      font-size: 1.5rem;
      color: #666;
      font-weight: 600;
    }
    .el-dialog__body {
      border-top: 1px solid #eee;
      .announcement-content {
        .content-title {
          background-color: #eee;
          padding: 10px;
          color: #999;
          font-size: 1.1rem;
        }
        .operation-bar {
          display: flex;
          justify-content: end;
          padding: 10px;
          .el-input {
            flex-basis: 60%;
            margin-right: 12px;
          }
          .el-button {
            flex: 0 0 auto;
          }
        }
        .button-box {
          display: flex;
        }
      }
    }

    .el-pagination {
      justify-content: center;
    }
  }
}
</style>
